import {ref} from "vue";
import {TEvent, TKeyboardEvent, TPList} from "../todo";
import {nanoid} from "nanoid";


export default function useCRUD(){
    const todolist = ref<TPList>([
        {id:nanoid(),todoName:'抽烟',checked:false},
        {id:nanoid(),todoName:'喝酒',checked:false},
        {id:nanoid(),todoName:'打代码',checked:false}
    ])

//新增todo
    const addTodo = (e:TKeyboardEvent)=>{
        todolist.value.push({
            id:nanoid(),
            todoName:e.target.value,
            checked:false
        })
        e.target.value = ''
    }

//删除todo
    const deleteTodo = (id:string)=>{
        todolist.value = todolist.value.filter(item=>item.id!==id)
    }

//单个todo的checked改变
    const todoChecked = (id:string,e:TEvent)=>{
        todolist.value = todolist.value.map(item=>{
            if(item.id===id){
                item.checked = e.target.checked
            }
            return item
        })
    }

//批量修改todo的状态
    const changeAllTodoChecked = (e:TEvent)=>{
        todolist.value = todolist.value.map(item=>{
            item.checked = e.target.checked
            return item
        })
    }

//清除已完成的todo
    const deleteALlCheckedTodo = ()=>{
        todolist.value = todolist.value.filter(item=>!item.checked)
    }

    return {todolist,addTodo,deleteTodo,todoChecked,changeAllTodoChecked,deleteALlCheckedTodo}
}